<template>
    <div class="nav-bar">
        <div class="nav-menu">
            <div class="nav-menu-item" @click="$router.push('/home')">
                首页
            </div>
            <div class="nav-menu-item" @click="$router.push('/job/intern')">
                实习职位
            </div>
            <div class="nav-menu-item" @click="$router.push('/job/formal')">
                正式职位
            </div>
        </div>
        <div class="user-section">
            <template v-if="!isLoggedIn">
                <el-button size="medium" type="primary" round @click="showLoginDialog">登录注册</el-button>
            </template>
            <template v-else>
                <div class="el-dropdown-link">
                    <el-avatar :size="40" :src="userInfo?.avatar || userAvatar"></el-avatar>
                    <span>{{ userInfo.nickname }}</span>
                    <span @click="$router.push('/user')">个人中心</span>
                    <span @click="logout">退出登录</span>
                </div>
            </template>
        </div>

        <!-- 登录注册弹窗 -->
        <el-dialog :title="dialogTitle" :visible.sync="dialogVisible" width="400px" center class="login-dialog">
            <el-tabs v-model="activeTab" @tab-click="handleTabClick" class="custom-tabs">
                <el-tab-pane label="登录" name="login">
                    <el-form :model="loginForm" :rules="loginRules" ref="loginForm" label-width="80px" class="custom-form">
                        <el-form-item label="用户名" prop="username">
                            <el-input v-model="loginForm.username" placeholder="请输入用户名" prefix-icon="el-icon-user"></el-input>
                        </el-form-item>
                        <el-form-item label="密码" prop="password">
                            <el-input v-model="loginForm.password" type="password" placeholder="请输入密码" prefix-icon="el-icon-lock"></el-input>
                        </el-form-item>
                        <el-form-item>
                            <el-button type="primary" @click="handleLogin" class="submit-btn" :loading="loading">登录</el-button>
                        </el-form-item>
                    </el-form>
                </el-tab-pane>
                <el-tab-pane label="注册" name="register">
                    <el-form :model="registerForm" :rules="registerRules" ref="registerForm" label-width="80px" class="custom-form">
                        <el-form-item label="用户名" prop="username">
                            <el-input v-model="registerForm.username" placeholder="请输入用户名" prefix-icon="el-icon-user"></el-input>
                        </el-form-item>
                        <el-form-item label="密码" prop="password">
                            <el-input v-model="registerForm.password" type="password" placeholder="请输入密码" prefix-icon="el-icon-lock"></el-input>
                        </el-form-item>
                        <el-form-item label="确认密码" prop="confirmPassword">
                            <el-input v-model="registerForm.password2" type="password" placeholder="请再次输入密码" prefix-icon="el-icon-lock"></el-input>
                        </el-form-item>
                        <el-form-item label="邮箱" prop="email">
                            <el-input v-model="registerForm.email" placeholder="请输入邮箱" prefix-icon="el-icon-message">
                                <el-button slot="append" @click="sendEmailCode" :disabled="emailCodeDisabled" class="code-btn">
                                    {{ emailCodeText }}
                                </el-button>
                            </el-input>
                        </el-form-item>
                        <el-form-item label="验证码" prop="code">
                            <el-input v-model="registerForm.code" placeholder="请输入验证码" prefix-icon="el-icon-key"></el-input>
                        </el-form-item>
                        <el-form-item>
                            <el-button type="primary" @click="handleRegister" class="submit-btn" :loading="loading">注册</el-button>
                        </el-form-item>
                    </el-form>
                </el-tab-pane>
            </el-tabs>
        </el-dialog>
    </div>
</template>

<script>
import { getLogin, getRegister, getEmailSend } from '@/api';

export default {
    name: 'NavBar',
    data() {
        // 密码确认验证
        const validateConfirmPassword = (rule, value, callback) => {
            if (value !== this.registerForm.password) {
                callback(new Error('两次输入的密码不一致'));
            } else {
                callback();
            }
        };

        return {
            activeIndex: '/',
            loading: false,
            dialogVisible: false,
            activeTab: 'login',
            dialogTitle: '用户登录',
            loginForm: {
                username: '',
                password: ''
            },
            registerForm: {
                username: '',
                password: '',
                password2: '',
                email: '2045718969@qq.com',
                code: ''
            },
            emailCodeDisabled: false,
            emailCodeText: '发送验证码',
            countdown: 60,
            loginRules: {
                username: [
                    { required: true, message: '请输入用户名', trigger: 'blur' },
                    { min: 3, max: 20, message: '长度在 3 到 20 个字符', trigger: 'blur' }
                ],
                password: [
                    { required: true, message: '请输入密码', trigger: 'blur' },
                    { min: 6, max: 20, message: '长度在 6 到 20 个字符', trigger: 'blur' }
                ]
            },
            registerRules: {
                username: [
                    { required: true, message: '请输入用户名', trigger: 'blur' },
                    { min: 3, max: 20, message: '长度在 3 到 20 个字符', trigger: 'blur' }
                ],
                password: [
                    { required: true, message: '请输入密码', trigger: 'blur' },
                    { min: 6, max: 20, message: '长度在 6 到 20 个字符', trigger: 'blur' }
                ],
                email: [
                    { required: true, message: '请输入邮箱', trigger: 'blur' },
                    { type: 'email', message: '请输入正确的邮箱地址', trigger: 'blur' }
                ],
                code: [
                    { required: true, message: '请输入验证码', trigger: 'blur' }
                ],
            },
            deliveryRecords: [], // 投递记录数据
            isLoggedIn: false, // 是否已登录
            userInfo: {}
        }
    },
    mounted() {
        this.judgeIsLogin();
        this.fetchDeliveryRecords();
    },
    watch: {
        '$route'(to) {
            this.activeIndex = to.path
        }
    },
    methods: {
        async sendEmailCode() {
            if (!this.registerForm.email) {
                this.$message.warning('请输入邮箱地址');
                return;
            }

            try {
                await getEmailSend(this.registerForm.email);
                this.$message.success('验证码已发送');
                this.emailCodeDisabled = true;
                this.startCountdown();
            } catch (error) {
                this.$message.error('发送验证码失败');
            }
        },
        startCountdown() {
            this.countdown = 60;
            const timer = setInterval(() => {
                this.countdown--;
                this.emailCodeText = `${this.countdown}秒后重试`;
                if (this.countdown <= 0) {
                    clearInterval(timer);
                    this.emailCodeDisabled = false;
                    this.emailCodeText = '发送验证码';
                }
            }, 1000);
        },
        judgeIsLogin() {
            const userInfo = JSON.parse(localStorage.getItem('userInfo'));
            this.isLoggedIn = userInfo != null;
            if (this.isLoggedIn) {
                this.userInfo = userInfo;
            }
        },
        showLoginDialog() {
            this.dialogVisible = true;
        },
        handleTabClick(tab) {
            this.dialogTitle = tab.label === '登录' ? '用户登录' : '用户注册';
        },
        handleLogin() {
            this.$refs.loginForm.validate(valid => {
                if (valid) {
                    this.loading = true;
                    getLogin(this.loginForm).then(res => {
                        this.$message.success('登录成功');
                        this.userInfo = res.data.user;
                        localStorage.setItem('token', res.data.token);
                        localStorage.setItem('userInfo', JSON.stringify(res.data.user));
                        this.loading = false;
                        this.dialogVisible = false;
                        this.isLoggedIn = true;
                        // 清空表单
                        this.$refs.loginForm.resetFields();
                    }).catch(err => {
                        this.$message.error(err.msg);
                        this.loading = false;
                    })
                } else {
                    return false;
                }
            });
        },
        handleRegister() {
            this.$refs.registerForm.validate(valid => {
                if (valid) {
                    this.loading = true;
                    getRegister(this.registerForm).then(res => {
                        this.$message.success('注册成功，请登录');
                        this.loading = false;
                        // 清空表单
                        this.$refs.loginForm.resetFields();
                        this.activeTab = 'login';
                        this.dialogTitle = '用户登录';
                        // 清空表单
                        this.$refs.registerForm.resetFields();
                    }).catch(err => {
                        this.$message.error(err.msg);
                        this.loading = false;
                    })

                } else {
                    return false;
                }
            });
        },
        logout() {
            this.$store.commit('SET_USERINFO', null);
            localStorage.removeItem('token');
            localStorage.removeItem('userInfo');
            this.isLoggedIn = false;
            this.$message.success('已退出登录');
        },
        async fetchDeliveryRecords() {
            if (this.isLoggedIn) {
                try {
                    // 这里需要调用获取投递记录的API
                    // const res = await getDeliveryRecords();
                    // this.deliveryRecords = res.data;
                } catch (error) {
                    this.$message.error('获取投递记录失败');
                }
            }
        }
    }
}
</script>

<style scoped>
.nav-bar {
    height: 60px;
    background: linear-gradient(135deg, #a8c0ff 0%, #e2b0ff 50%, #f9d423 100%);
    padding: 0 100px;
    display: flex;
    justify-content: space-between;
    align-items: center;
    box-shadow: 0 2px 10px rgba(0, 0, 0, 0.05);
    z-index: 1000;
    box-sizing: border-box;
    position: relative;
    overflow: hidden;
}

.nav-bar::before {
    content: '';
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    background: linear-gradient(135deg, rgba(255,255,255,0.3) 0%, rgba(255,255,255,0) 100%);
    transform: translateX(-100%);
    transition: transform 0.6s cubic-bezier(0.4, 0, 0.2, 1);
}

.nav-bar:hover::before {
    transform: translateX(100%);
}

.nav-menu {
    display: flex;
    justify-content: space-between;
    align-items: center;
    background-color: transparent;
}

.nav-menu-item {
    margin-right: 50px;
    color: white;
    font-size: 16px;
    font-weight: 500;
    position: relative;
    padding: 5px 10px;
    cursor: pointer;
    transition: all 0.3s ease;
}

.nav-menu-item::after {
    content: '';
    position: absolute;
    bottom: 0;
    left: 0;
    width: 0;
    height: 2px;
    background: #e6f7ff;
    transition: width 0.3s ease;
}

.nav-menu-item:hover {
    transform: translateY(-2px);
    text-shadow: 0 0 10px rgba(255, 255, 255, 0.8);
    color: #e6f7ff;
}

.nav-menu-item:hover::after {
    width: 100%;
    background: #e6f7ff;
}

.user-section {
    display: flex;
    align-items: center;
    gap: 20px;
}

.user-section .el-button {
    background: rgba(255, 255, 255, 0.2);
    border: none;
    color: white;
    transition: all 0.3s ease;
}

.user-section .el-button:hover {
    background: rgba(255, 255, 255, 0.3);
    transform: translateY(-2px);
    box-shadow: 0 4px 8px rgba(0, 0, 0, 0.2);
}

.el-dropdown-link {
    cursor: pointer;
    display: flex;
    align-items: center;
    font-size: 0.9rem;
    color: white;
}

.el-dropdown-link span {
    margin-left: 10px;
    transition: all 0.3s ease;
}

.el-dropdown-link:hover span {
    text-shadow: 0 0 10px rgba(255, 255, 255, 0.8);
    color: #e6f7ff;
}

/* 登录注册弹窗样式 */
.login-dialog {
    border-radius: 20px;
    overflow: hidden;
    opacity: 0.95;
}

.login-dialog :deep(.el-dialog) {
    border-radius: 20px;
    overflow: hidden;
}

.login-dialog :deep(.el-dialog__header) {
    padding: 20px;
    background: linear-gradient(135deg, #a8c0ff 0%, #e2b0ff 50%, #f9d423 100%);
    margin: 0;
    opacity: 0.95;
    border-top-left-radius: 20px;
    border-top-right-radius: 20px;
}

.login-dialog :deep(.el-dialog__body) {
    padding: 30px;
    background: #f8f9fa;
    opacity: 0.95;
    border-bottom-left-radius: 20px;
    border-bottom-right-radius: 20px;
}

.custom-tabs :deep(.el-tabs__nav) {
    width: 100%;
    display: flex;
    justify-content: center;
}

.custom-tabs :deep(.el-tabs__item) {
    padding: 0 20px;
    height: 40px;
    line-height: 40px;
    font-size: 16px;
    color: #606266;
}

.custom-tabs :deep(.el-tabs__item.is-active) {
    color: #409EFF;
    font-weight: 600;
}

.custom-tabs :deep(.el-tabs__active-bar) {
    background-color: #409EFF;
}

.custom-form :deep(.el-form-item__label) {
    color: #606266;
    font-weight: 500;
}

.custom-form :deep(.el-input__inner) {
    border-radius: 12px;
    border: 1px solid #dcdfe6;
    transition: all 0.3s ease;
    opacity: 0.95;
}

.submit-btn {
    width: 100%;
    height: 40px;
    border-radius: 12px;
    background: linear-gradient(135deg, #a8c0ff 0%, #e2b0ff 50%, #f9d423 100%);
    border: none;
    color: white;
    font-size: 16px;
    font-weight: 500;
    transition: all 0.3s ease;
    opacity: 0.95;
}

.code-btn {
    background: #f0f2f5;
    border: none;
    color: #606266;
    transition: all 0.3s ease;
    opacity: 0.95;
    border-radius: 8px;
}

.code-btn:hover {
    background: #e4e7ed;
    color: #409EFF;
    opacity: 1;
}

.code-btn:disabled {
    background: #f5f7fa;
    color: #c0c4cc;
    opacity: 0.8;
}

.delivery-records {
    max-height: 400px;
    overflow-y: auto;
}

.delivery-records h3 {
    margin-bottom: 15px;
    text-align: center;
}
</style>